package net.mujiwulian.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import net.mujiwulian.entity.Document;
import net.mujiwulian.service.DocumentService;
import net.mujiwulian.vo.PageQuery;
import net.mujiwulian.vo.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * @Author: silence
 * @Description:
 * @Date:Create：in 2019/12/30 12:44
 */
@Slf4j
@RestController
@RequestMapping("/document")
public class DocumentController {

    @Value("${file-path}")
    private String filePath;

    private final DocumentService documentService;

    public DocumentController(DocumentService documentService) {
        this.documentService = documentService;
    }

    @PostMapping("/select")
    public Result<IPage<Document>> select(@RequestBody PageQuery<Document> pageQuery) {
        String type = pageQuery.getT() == null ? null : pageQuery.getT().getType();
        LambdaQueryWrapper<Document> lq = Wrappers.lambdaQuery();
        lq.and(StringUtils.isNotEmpty(pageQuery.getKeywords()), i -> i.like(Document::getAuthor, pageQuery.getKeywords()).or().like(Document::getTitle, pageQuery.getKeywords()));
        lq.eq(StringUtils.isNotEmpty(type), Document::getType, type);
        lq.orderByDesc(Document::getCreateTime);
        return new Result<>(Result.CodeStatus.OK, "获取文章信息", documentService.page(pageQuery.getPageCondition(), lq));
    }

    @PostMapping("/selectById")
    public Result<Document> select(Integer id) {
        return new Result<>(Result.CodeStatus.OK, "获取文章信息", documentService.getById(id));
    }

    @PostMapping("/delete")
    public Result<Void> delete(@RequestBody List<Integer> ids) {
        List<Document> list = documentService.list(new QueryWrapper<Document>().in("id", ids).select("cover_url"));
        list.forEach(document -> log.warn("删除文件:" + document.getCoverUrl() + "-----" + new File(this.filePath + document.getCoverUrl()).delete()));
        return new Result<>("删除文章", documentService.removeByIds(ids));
    }

    @PostMapping("/insertOrUpdate")
    public Result<Void> insertOrUpdate(Document document) {
        Document dt = null;
        if (document.getId() != null) {
            dt = documentService.getById(document.getId());
        } else {
            if (!documentService.list(new QueryWrapper<Document>().eq("title", document.getTitle())).isEmpty()) {
                return new Result<>(Result.CodeStatus.FAIL, "标题已存在");
            }
            document.setCreateTime(LocalDateTime.now());
        }
        try {
            if (document.getCover() != null) {
                String path = "/files/document/" + UUID.randomUUID().toString() + document.getCover().getOriginalFilename();
                FileUtils.copyInputStreamToFile(document.getCover().getInputStream(), new File(this.filePath + path));
                document.setCoverUrl(path);
                if (dt != null) {
                    File deleteFile = new File(this.filePath + dt.getCoverUrl());
                    log.warn("删除文件:" + dt.getCoverUrl() + "-----" + deleteFile.delete());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result<>(Result.CodeStatus.FAIL, "网络异常");
        }
        return new Result<>("操作", documentService.saveOrUpdate(document));
    }


}
